package com.example.demo.controllers.auth;

import com.example.demo.exception.AccessDeniedException;
import com.example.demo.exception.ErrorResponse;
import com.example.demo.exception.ResourceNotFoundException;
import com.example.demo.model.dto.ProfileUpdateDTO;
import com.example.demo.model.dto.ChangePasswordDTO;
import com.example.demo.model.dto.UserProfileResponse;
import com.example.demo.model.entity.user.User;
import com.example.demo.service.ProfileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.github.pagehelper.PageInfo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/profile")
@RequiredArgsConstructor
@SecurityRequirement(name = "bearerAuth")
@Tag(name = "用户信息管理", description = "用户信息管理接口")
@Slf4j
public class ProfileController {

    private final ProfileService profileService;

    @GetMapping("/me")
    @Operation(summary = "获取当前用户资料", description = "获取当前登录用户的详细信息")
    public ResponseEntity<User> getCurrentUserProfile() {
        try {
            User user = profileService.getCurrentUserProfile();
            return ResponseEntity.ok(user);
        } catch (ResourceNotFoundException e) {
            log.error("获取当前用户资料时出错: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }

    @PatchMapping("/update")
    @Operation(summary = "更新用户资料", description = "更新当前用户的个人资料信息")
    public ResponseEntity<?> updateUserProfile(
            @Valid @RequestBody ProfileUpdateDTO updateDTO) {
        try {
            User updatedUser = profileService.updateCurrentUserProfile(updateDTO);

            // 确保返回的对象数据完整
            updatedUser.validateDataIntegrity();

            // 创建简化响应DTO，只返回必要字段
            UserProfileResponse response = UserProfileResponse.builder()
                    .userId(updatedUser.getUserId())
                    .username(updatedUser.getUsername())
                    .name(updatedUser.getName())
                    .email(updatedUser.getEmail())
                    .phone(updatedUser.getPhone())
                    .userType(updatedUser.getUserType())
                    .status(updatedUser.getStatus())
                    .avatar(updatedUser.getAvatar())
                    .createTime(updatedUser.getCreateTime())
                    .build();

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新用户资料时出错: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ErrorResponse( HttpStatus.INTERNAL_SERVER_ERROR.value(),  // status
                            "更新用户资料失败: " + e.getMessage(),        // message
                            "USER_PROFILE_UPDATE_ERROR"               // errorCode
                    ));
        }
    }

    @PostMapping("/change-password")
    @Operation(summary = "修改密码", description = "修改当前用户的登录密码")
    public ResponseEntity<Void> changePassword(
            @Valid @RequestBody ChangePasswordDTO changePasswordDTO) {
        try {
            profileService.changeCurrentUserPassword(changePasswordDTO);
            return ResponseEntity.ok().build();
        } catch (IllegalArgumentException e) {
            log.error("修改密码时出错: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        } catch (Exception e) {
            log.error("修改密码时发生未知错误: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @DeleteMapping("/deactivate")
    @Operation(summary = "注销账户", description = "当前用户自行注销账户")
    public ResponseEntity<Void> deactivateAccount() {
        try {
            profileService.deactivateCurrentUserAccount();
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            log.error("注销账户时出错: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @DeleteMapping("/delete/{userId}")
    @Operation(summary = "删除用户账户",
            description = "管理员可以删除任何用户，教师可以删除关联的学生账户")
    public ResponseEntity<Void> deleteUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable Long userId) {
        try {
            profileService.deleteUserWithPermissionCheck(userId);
            return ResponseEntity.noContent().build();
        } catch (AccessDeniedException e) {
            log.error("删除用户账户时权限不足: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        } catch (ResourceNotFoundException e) {
            log.error("删除用户账户时用户不存在: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        } catch (Exception e) {
            log.error("删除用户账户时发生未知错误: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GetMapping("/admin/users")
    @Operation(summary = "获取所有用户信息",
            description = "管理员获取系统中所有用户的信息（分页）")
    public ResponseEntity<PageInfo<User>> getAllUsers(
            @Parameter(description = "页码，从1开始")
            @RequestParam(defaultValue = "1") int pageNum,

            @Parameter(description = "每页数量")
            @RequestParam(defaultValue = "20") int pageSize) {
        try {
            PageInfo<User> pageInfo = profileService.getAllUsers(pageNum, pageSize);
            return ResponseEntity.ok(pageInfo);
        } catch (AccessDeniedException e) {
            log.error("获取所有用户信息时权限不足: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        } catch (Exception e) {
            log.error("获取所有用户信息时发生未知错误: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GetMapping("/admin/search")
    @Operation(summary = "搜索用户",
            description = "根据用户名或邮箱搜索用户（管理员权限）")
    public ResponseEntity<List<User>> searchUsers(
            @Parameter(description = "搜索关键词", required = true)
            @RequestParam String keyword) {
        try {
            List<User> users = profileService.searchUsers(keyword);
            return ResponseEntity.ok(users);
        } catch (AccessDeniedException e) {
            log.error("搜索用户时权限不足: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        } catch (Exception e) {
            log.error("搜索用户时发生未知错误: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}